//
//  CZNetWorkTools.swift
//  Swift -- 微博
//
//  Created by sks on 16/6/26.
//  Copyright © 2016年 mohaha. All rights reserved.
//

import UIKit
import AFNetworking

//设置请求方式
enum MethodType : String {

    case GET = "GET"
    case POST = "POST"

}

class CZNetWorkTools: AFHTTPSessionManager {
    
    //单例对象
    static let sharedTools : CZNetWorkTools = {
    let tools = CZNetWorkTools()
    //添加解析格式
    tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
    
    return tools
    
    }()
    
    //请求数据方法
    func requeset(method:MethodType,urlString: String,parmeters:AnyObject?,success:(response:AnyObject?)->(),failure:(error:NSError)->()) -> () {
        if method == .GET {
            
            self.GET(urlString, parameters: parmeters, progress: nil, success: { (_, res) in
                
                success(response: res)
                
                }, failure: { (_, err) in
                    
                failure(error: err)
                    
            })
            
        }else{
        
            self.POST(urlString, parameters: parmeters, progress: nil, success: { (_, res) in
                success(response: res)
                }, failure: { (_, err) in
                    failure(error: err)
            })
        
        }
    }

}

extension CZNetWorkTools{
    
    //请求token方法
    func oauthLoadUserAccount(code:String,success:(response:AnyObject?)->(),failure:(error:NSError)->()){
       //请求的URL
        let urlString = "https://api.weibo.com/oauth2/access_token"
       //请求所需的参数
        let params = [
        
            "client_id":APPKEY,
            "client_secret":APPSECRET,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":redirect_uri
        ]
       
        self.requeset(.POST, urlString: urlString, parmeters: params, success: success, failure: failure)
        
    }
    
    //请求个人信息数据
    func oauthLoadUserInfo(userAccount:CZUserAccount,success:(response:AnyObject?)->(),failure:(error:NSError)->()) {
        
        //请求的URL
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        //请求所需的参数
        let parmas = [
        
             "access_token":userAccount.access_token!,
             "uid":userAccount.uid!
        ]
        
        self.requeset(.GET, urlString: urlString, parmeters: parmas, success: success, failure: failure)
        
        
    }
   

}

// 请求首页数据
extension CZNetWorkTools {
    func homeLoadStatusData(success:(response:AnyObject?)->(),failure:(error:NSError)->()){
        // 请求url
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        // 请求参数
        let params = ["access_token": CZUserAccountTools.sharedTools.accessToken!]
        // 发送请求
        requeset(.GET, urlString: urlString, parmeters: params, success: success, failure: failure)
    }
}

